unit UntDm;

interface

uses
  SysUtils, Classes, FIBDatabase, pFIBDatabase,
  IdHTTP, ExtCtrls, FIBQuery, pFIBQuery, ZipForge, IdBaseComponent, IdComponent,
  IdTCPConnection, IdTCPClient;

type
  TDM = class(TDataModule)
    HTTP: TIdHTTP;
    DB: TpFIBDatabase;
    QryCotacoesDiarias: TpFIBQuery;
    TrCotacoesDiarias: TpFIBTransaction;
    Timer1: TTimer;
    TrCotacoes: TpFIBTransaction;
    QryCotacoes: TpFIBQuery;
    Zip: TZipForge;
    procedure DataModuleCreate(Sender: TObject);
    procedure Timer1Timer(Sender: TObject);
  private
    procedure FormatarArquivo1(Arq, acao: string);

  public
    path: string;
    function download(Url, Arq: string): Boolean;
  end;

var
  DM: TDM;

implementation

uses Forms, UntMsg;

{$R *.dfm}

procedure TDM.DataModuleCreate(Sender: TObject);
begin
  path := ExtractFilePath(Application.ExeName);
  try
    DB.Close;
    DB.DBName := path + '\dados.fdb';
    DB.Open;
  except
    MsgErro('Falha ao Conectar com o Banco de Dados');
  end;
end;

function TDM.download(Url,Arq: string): Boolean;
var MyFile: TFileStream;
    s: Int64;
begin
  Result := False;
  Try
    try
      MyFile := TFileStream.Create(Arq, fmCreate);
      HTTP.Get(Url,MyFile);
      Result := True;
    except

    end;
  Finally
    s := MyFile.Size;
    MyFile.Free;
    if (s = 0) then begin
      DeleteFile(Arq);
      Result := False;
    end;
  End;
end;

function getDate(d: string):TDate;
begin
  d := StringReplace(d,'jan','01',[rfIgnoreCase]);
  d := StringReplace(d,'fev','02',[rfIgnoreCase]);
  d := StringReplace(d,'mar','03',[rfIgnoreCase]);
  d := StringReplace(d,'abr','04',[rfIgnoreCase]);
  d := StringReplace(d,'mai','05',[rfIgnoreCase]);
  d := StringReplace(d,'jun','06',[rfIgnoreCase]);
  d := StringReplace(d,'jul','07',[rfIgnoreCase]);
  d := StringReplace(d,'ago','08',[rfIgnoreCase]);
  d := StringReplace(d,'set','09',[rfIgnoreCase]);
  d := StringReplace(d,'out','10',[rfIgnoreCase]);
  d := StringReplace(d,'nov','11',[rfIgnoreCase]);
  d := StringReplace(d,'dez','12',[rfIgnoreCase]);

  result := EncodeDate(StrToInt(Copy(d,1,4)),StrToInt(Copy(d,6,2)),StrToInt(Copy(d,9,2)));
end;

procedure TDM.FormatarArquivo1(Arq,acao: string);
var f: TextFile;
    d,s: string;
    T1,T2: TStrings;
    i: Integer;
    Data: TDate;
    valor: Currency;
begin
  try
    T1 := TStringList.Create;
    T2 := TStringList.Create;
    T1.Delimiter := '|';
    T2.Delimiter := '@';
    try
      AssignFile(F,Arq);
      Reset(F);
      Readln(F,s);
      d := copy(s,pos('D',s)+2,pos('&V=',s)-3);
      Data := getDate(d);

      s := StringReplace(s,copy(s,1,pos('&V=',s)+2),'',[rfReplaceAll]);
      T1.DelimitedText := s;

      if not QryCotacoesDiarias.Transaction.InTransaction then
        QryCotacoesDiarias.Transaction.StartTransaction;

      for I := 0 to (T1.Count-1) do begin
        T2.DelimitedText := T1[i];
        if T2.Count <> 3 then Continue;

        DecimalSeparator := '.';
        valor := StrToCurr(T2[1]);
        DecimalSeparator := ',';
        if (valor > 0) then begin
          with QryCotacoesDiarias do begin
            Prepare;
            ParamByName('ACAO').AsString := acao;
            ParamByName('DATA').AsDateTime := Data;
            ParamByName('HORA').AsString := T2[0];
            ParamByName('VALOR').AsCurrency := valor;
            ExecQuery;
          end;
        end;
      end;
      QryCotacoesDiarias.Transaction.Commit;
    except
    end;
  finally
    T1.Free;
    T2.Free;
    CloseFile(F);
  end;
end;

procedure TDM.Timer1Timer(Sender: TObject);
var arq,acao: string;
begin
  if (not DB.Connected) then Exit;
  
  try
    Timer1.Enabled := False;
    Timer1.Interval := 30000;
    arq := DM.path + '\2.csv';
    DeleteFile(arq);
    acao := 'PETR4';
    download('http://www.bmfbovespa.com.br/Pregao-Online/ExecutaAcaoCarregarDadosPapeis.asp?CodDado=' + acao, arq);
    if FileExists(arq) then FormatarArquivo1(Arq,acao);
  finally
    Timer1.Enabled := True;
    DeleteFile(arq);
  end;
end;

end.
